package com.feng.study.demo.chatgpt;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class ChatGPTBot {
    private final String apiKey = "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";
    private final OkHttpClient httpClient = new OkHttpClient();
    private final String apiUrl = "https://api.openai.com/v1/engines/davinci-codex/completions";

    public String generateResponse(String message) throws IOException, JSONException {
        JSONObject json = new JSONObject()
                .put("prompt", message)
                .put("max_tokens", 50)
                .put("temperature", 0.7)
                .put("n", 1)
                .put("stop", "\n");
        String string = json.toString();
        System.out.println(string);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), string);
        Request request = new Request.Builder()
                .url(apiUrl)
                .addHeader("Authorization", "Bearer " + apiKey)
                .post(body)
                .build();

        Response response = httpClient.newCall(request).execute();
        String responseBody = response.body().string();
        JSONObject jsonResponse = new JSONObject(responseBody);
        JSONArray choices = jsonResponse.getJSONArray("choices");
        JSONObject firstChoice = choices.getJSONObject(0);
        String generatedText = firstChoice.getStr("text");

        return generatedText;
    }
}
